#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>  
#include <stdlib.h>  
#include <stdbool.h>  
#include <string.h>  
#include <ctype.h>  

#define MAX_SIZE 100  

typedef struct Stack {
    int top;
    unsigned capacity;
    int* array;
} Stack;

Stack* createStack(unsigned capacity) {
    Stack* stack = (Stack*)malloc(sizeof(Stack));
    if (!stack) exit(EXIT_FAILURE);
    stack->capacity = capacity;
    stack->top = -1;
    stack->array = (int*)malloc(stack->capacity * sizeof(int));
    if (!stack->array) exit(EXIT_FAILURE);
    return stack;
}

bool isFull(Stack* stack) {
    return stack->top == stack->capacity - 1;
}

bool isEmpty(Stack* stack) {
    return stack->top == -1;
}

void push(Stack* stack, int item) {
    if (isFull(stack)) {
        fprintf(stderr, "Stack is full\n");
        exit(EXIT_FAILURE);
    }
    stack->array[++stack->top] = item;
}

int pop(Stack* stack) {
    if (isEmpty(stack)) {
        fprintf(stderr, "Stack is empty\n");
        exit(EXIT_FAILURE);
    }
    return stack->array[stack->top--];
}

int peek(Stack* stack) {
    if (isEmpty(stack)) {
        fprintf(stderr, "Stack is empty\n");
        exit(EXIT_FAILURE);
    }
    return stack->array[stack->top];
}

int precedence(char op) {
    if (op == '+' || op == '-')
        return 1;
    if (op == '*' || op == '/')
        return 2;
    return 0;
}

int applyOp(int a, int b, char op) {
    switch (op) {
    case '+': return a + b;
    case '-': return a - b;
    case '*': return a * b;
    case '/': if (b != 0) return a / b;
        // handle division by zero  
    default: return 0;
    }
}

int evaluatePostfix(char* exp) {
    Stack* values = createStack(MAX_SIZE);
    int i, val1, val2;
    char op;

    for (i = 0; exp[i]; ++i) {
        if (isdigit(exp[i])) {
            // Assuming the numbers are single digits for simplicity  
            push(values, exp[i] - '0');
        }
        else {
            val2 = pop(values);
            val1 = pop(values);
            op = exp[i];
            push(values, applyOp(val1, val2, op));
        }
    }

    int result = pop(values);
    free(values->array);
    free(values);
    return result;
}

int main() {
    char expression[] = "231*+8-"; // (2 + 3 * 1) - 8  
    printf("Result: %d\n", evaluatePostfix(expression));
    return 0;
}